package com.xujichang.base.extensions

import android.os.SystemClock
import android.util.Log
import android.view.View
import android.widget.EditText
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
/*隐藏如软键盘*/
fun View.hideKeyBoard() {
    val controller = ViewCompat.getWindowInsetsController(this)
    controller?.also {
        controller.hide(WindowInsetsCompat.Type.ime())
    }
}

/**
 * 防止快速重复点击事件
 */
fun View.click(clickOutTimeMills: Long = 1000L, onClick: (View) -> Unit) {
    setOnClickListener(ClickProxy(clickOutTimeMills, onClick))
}

class ClickProxy(private val clickOutTimeMills: Long, private val action: (View) -> Unit) :
    View.OnClickListener {
    private val lastClickMills = AtomicLong(0L)

    override fun onClick(v: View) {
        val uptimeMills = SystemClock.uptimeMillis()
        if ((uptimeMills - lastClickMills.get()) < clickOutTimeMills) {
            Logs.d(tag, "忽略此次点击..")
            return
        }
        action(v)
        lastClickMills.set(uptimeMills)
    }
}

/**
 * 输入长度限制
 */
fun EditText.wordLimit(max: Int, onLimit: () -> Unit) {
    var deleteStart = 0
    var deleteCount = 0
    val shouldDelete = AtomicBoolean(false)
    addTextChangedListener(
        onTextChanged = { _, start, before, count ->
            val newLength = text.length
            //大于所输入额度最大长度
            if (newLength <= max) {
                shouldDelete.set(false)
                return@addTextChangedListener
            }
            shouldDelete.set(true)
            deleteStart = start
            deleteCount = count
        }) {
        if (shouldDelete.get()) {
            onLimit()
            text.delete(deleteStart, deleteStart + deleteCount)
        }
    }
}
